const { Worker,workerData, parentPort } = require("worker_threads");

const { imgData, imgData2, Narrow, name } = workerData;

let WorkerList = [];

const  config=require('./config.json');

async function start() {
    let maxW = imgData.length;
    let maxH = imgData[0].length;

    let w = imgData2.length;
    let h = imgData2[0].length;
    let map = new Map();

    let prom = [];


    //开十个线程
    let threadNum=splitRange(0, maxW * maxH,  config.线程数);

    console.log('LPTEXT ' + name + ' 最大次数-->', maxW * maxH, '  最大可信度-->', w * h , '  线程最大任务数-->', threadNum[0].end);

    WorkerList=[];

    console.time(name + '-->for')

    for (let i = 0; i < threadNum.length; i++) {
        const element = threadNum[i];
        prom.push(runComputeThreads({
            ...element,imgData, imgData2, Narrow, name,maxW,maxH,w,h
        }).then((res) => {
            console.log(name +'线程 '+i+' 完成');
            res.map.forEach((value, key) => {
                value['maxReliability']=(w * h);

                map.set(key,value);
            });

            // console.log('LPTEXT',i,res);
            if(res.isFinish){
                //结束所有线程
                WorkerList.forEach((element) => {
                    element.postMessage('结束线程');
                    // console.log('LPTEXT',element);
                });
            }

        }));
    }


    await Promise.all(prom)
    console.timeEnd(name + '-->for')


    let posData = { reliability: 0 };
    map.forEach((value, key) => {
        if (value.reliability > posData.reliability) {
            posData = value;
        }
    });
    return posData;
}


start().then((posData) => {
    parentPort.postMessage(posData);
});

function runComputeThreads(workerData) {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./computeThreads.js', { workerData });
        WorkerList.push(worker);
        worker.on('message', (res) => {
            worker.terminate();
            resolve(res);
        });
        worker.on('error', (err) => {
            worker.terminate();
            console.log(err)
            reject(err)
        });
        worker.on('exit', (code) => {
            worker.terminate();
            resolve({isFinish:false,map:new Map()});
            // console.log('exit code',code)
            // if (code !== 0)reject(new Error(`Worker stopped with exit code ${code}`));
        });
    });
}

function splitRange(start, end, numParts) {
    const rangeSize = Math.ceil((end - start + 1) / numParts);
    const ranges = [];

    for (let i = 0; i < numParts; i++) {
        const rangeStart = start + i * rangeSize;
        const rangeEnd = Math.min(rangeStart + rangeSize - 1, end);
        ranges.push({ start: rangeStart, end: rangeEnd });
    }

    return ranges;
}









